package top.gugulh.jx.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;

public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        String text = msg.text();
        clients.writeAndFlush(new TextWebSocketFrame("[服务器在" + LocalDateTime.now()
                + "接受到消息,消息为: " + text + "]"));
    }

    /**
     * 当客户端连接服务端之后,获取客户端的channel,并放入channelGroup中进行管理
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        clients.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        // 当触发handlerRemoved,ChannelGroup会自动触发移除对应的客户端Channel
        // clients.remove(ctx.channel());
        System.out.println("客户端断开,channel对应的长id: " + ctx.channel().id().asLongText());
        System.out.println("客户端断开,channel对应的短id: " + ctx.channel().id().asShortText());

    }
}
